package com.example.mycarcalling.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.track.TraceAnimationListener;
import com.baidu.mapapi.map.track.TraceOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.lib_cache.model.Application;
import com.example.lib_cache.model.Guide;
import com.example.lib_cache.model.Navigation;
import com.example.lib_cache.model.Order;
import com.example.lib_cache.model.User;
import com.example.lib_cache.service.ApiService;
import com.example.lib_cache.viewmodel.PickUpActivityViewModel;
import com.example.lib_cache.viewmodel.WaitingActivityViewModel;
import com.example.lib_common.util.MarkMoveUtil;
import com.example.lib_common.util.MileageUtils;
import com.example.lib_common.util.SpUtils;
import com.example.mycarcalling.R;
import com.example.mycarcalling.databinding.ActivityPickUpBinding;
import com.netease.nim.uikit.api.NimUIKit;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PickUpActivity extends AppCompatActivity {

    private final static String  TAG = PickUpActivity.class.getSimpleName();

    private Context context = null;

    private ActivityPickUpBinding activityPickUpBinding = null;
    private PickUpActivityViewModel pickUpActivityViewModel = null;

    private PickUpConfirmDialog pickUpConfirmDialog = null;

    private BaiduMap baiduMap = null;
    private TraceOptions traceOptions = null;

    private Timer requestTimer = null;

    private BitmapDescriptor bitmap = null;
    private BitmapDescriptor passengerBitmap = null;
    private MarkerOptions markerOptions = null;
    private Marker marker = null;
    private MarkMoveUtil markMoveUtil = null;

    @Inject
    ApiService apiService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityPickUpBinding = DataBindingUtil.setContentView(this,
                        R.layout.activity_pick_up);
        context = this;
        initView();
        initData();
        initObserve();
        initRequest();
        initListener();
        initTimer();

//        startMyTest2();




    }

    private void initRequest(){

        pickUpActivityViewModel.requestDriverAccount(apiService,context);
        pickUpActivityViewModel.requestNavigation(apiService,context);
        //仅加载时一次请求
        pickUpActivityViewModel.requestOrder(apiService,context);

    }

    private void initTimer(){
        //初始化定时器
        requestTimer = new Timer();
        Log.d(TAG,"5秒后开始执行：每6秒获取一次坐标数据");
        //5秒后开始执行：每6秒获取一次坐标数据
        requestTimer.schedule(new TimerTask() {
            public void run() {
                Log.d(TAG,"发起请求");
                pickUpActivityViewModel.requestDriverLocation(apiService,context);
            }
        }, 5000,6000);
    }

    private void initView(){
        setTitle("等待司机");

        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        pickUpActivityViewModel = viewModelProvider.
                get(PickUpActivityViewModel.class);


        //地图初始化
        baiduMap = activityPickUpBinding.mapviewPickUp.getMap();
        baiduMap.setTrafficEnabled(true);
        baiduMap.setMyLocationEnabled(true);

        //设置车辆图标
        bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_car);
        //乘客图标
        passengerBitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding);

        //初始化坐标参数
        LatLng latLng = baiduMap.getMapStatus().target;
        //准备 marker option 添加 marker 使用
        markerOptions = new MarkerOptions().icon(bitmap).position(latLng);
        //获取添加的 marker 这样便于后续的操作
        marker = (Marker) baiduMap.addOverlay(markerOptions);

        markMoveUtil = new MarkMoveUtil(
                1000,
                activityPickUpBinding.mapviewPickUp,
                marker,context);

        pickUpConfirmDialog = new PickUpConfirmDialog(context);


    }

    private void initData(){
        //初始化动态轨迹
        traceOptions = new TraceOptions();
        traceOptions.animationTime(5000);
        traceOptions.animate(true);
        traceOptions.animationType(TraceOptions.TraceAnimateType.TraceOverlayAnimationEasingCurveLinear);
        traceOptions.color(0xAAFF0000);
        traceOptions.width(10);
//        traceOptions.points(new ArrayList<>());
    }

    private void initListener(){
        activityPickUpBinding.btnCommunication.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,pickUpActivityViewModel.getDriverAccount().getValue());
                if(pickUpActivityViewModel.getDriverAccount().getValue() != null){
                    Log.d(TAG,"打开网易云信IM即时通信");

                    NimUIKit.startP2PSession(
                            context,
                            pickUpActivityViewModel.getDriverAccount().getValue());
                }
            }
        });

        activityPickUpBinding.btnPickUpConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"确认上车");
                pickUpConfirmDialog.show();
            }
        });

        pickUpConfirmDialog.getBtn_confirm().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickUpActivityViewModel.requestPickUp(apiService,context);
            }
        });
    }

    private void initObserve(){

        pickUpActivityViewModel.getNavigationMutableLiveData()
                .observe(this, new Observer<Navigation>() {
            @Override
            public void onChanged(Navigation navigation) {
                //更新上车点UI
                //自适应地图缩放视野
                //设置缩放级别
                    //乘客坐标
                    LatLng ll1 = new LatLng(
                            pickUpActivityViewModel.
                                    getNavigationMutableLiveData().getValue().getsLatitude(),
                            pickUpActivityViewModel
                                    .getNavigationMutableLiveData().getValue().getsLogitude());
                    //乘客上车点
                    LatLng ll2 = new LatLng(
                            navigation.getStartLatitude(),navigation.getStartLongitude());
                    addMarkerToMap(ll2,"乘客上车点");

                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll1);
                    builder.zoom(16);
                    baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        });

        pickUpActivityViewModel.getGuideMutableLiveData().observe(this, new Observer<Guide>() {
            @Override
            public void onChanged(Guide guide) {
                //更新轨迹UI
//                Log.d(TAG,"司机经度:"+guide.getGuiDriverLongitude());
//                Log.d(TAG,"司机纬度："+guide.getGuiDriverLatitude());
                //更新司机距离UI
                LatLng p1 = new LatLng(guide.getGuiDriverLatitude(),guide.getGuiDriverLongitude());
                LatLng p2 = new LatLng(
                        pickUpActivityViewModel.
                                getNavigationMutableLiveData().getValue().getsLatitude(),
                        pickUpActivityViewModel
                                .getNavigationMutableLiveData().getValue().getsLogitude());
                activityPickUpBinding.tvDistancePickUp.setText(
                        MileageUtils.meterToKilometers((int) DistanceUtil.getDistance(p1,p2)));

                //将司机位置加入经、纬度集合
                pickUpActivityViewModel.swapLatLng(
                        guide.getGuiDriverLongitude(),guide.getGuiDriverLatitude());
                Log.d(TAG,"olderll:"+pickUpActivityViewModel.getOrderLL().longitude+" "+pickUpActivityViewModel.getOrderLL().latitude);
                Log.d(TAG,"newll:"+pickUpActivityViewModel.getNewLL().longitude+" "+pickUpActivityViewModel.getNewLL().latitude);

                //至少设置两个坐标数据
                if(!pickUpActivityViewModel.getSwap()){
//                    自适应地图缩放视野
//                    设置缩放级别
                    LatLngBounds.Builder builder = new LatLngBounds.Builder();
                    //乘客坐标
                    LatLng ll1 = new LatLng(
                            pickUpActivityViewModel.
                                    getNavigationMutableLiveData().getValue().getsLatitude(),
                            pickUpActivityViewModel
                                    .getNavigationMutableLiveData().getValue().getsLogitude());
                    //司机坐标
                    LatLng ll2 = new LatLng(guide.getGuiDriverLatitude(),
                            guide.getGuiDriverLongitude());
                    builder.include(ll1);
                    builder.include(ll2);
                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngBounds(builder.build());
                    baiduMap.setMapStatus(mapStatusUpdate);
                    MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(-0.8f);
                    baiduMap.setMapStatus(msu);
                    marker.setPosition(ll2);
                    pickUpActivityViewModel.setSwap(true);
                }
                //设置车辆移动
                markMoveUtil.initLatlngData(
                        pickUpActivityViewModel.getOrderLL(),
                        pickUpActivityViewModel.getNewLL());
                markMoveUtil.moveLooper();


            }
        });

        pickUpActivityViewModel.getOrderMutableLiveData().observe(this, new Observer<Order>() {
            @Override
            public void onChanged(Order order) {
                Log.d(TAG,"用订单获取司机信息");
                pickUpActivityViewModel.requestPersonInfo(
                        apiService,context,order.getDeliveryDriver());

            }
        });

        pickUpActivityViewModel.getUserMutableLiveData().observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                pickUpActivityViewModel.requestApplication(apiService,context,user.getId());
            }
        });

        pickUpActivityViewModel.getApplicationMutableLiveData().observe(this, new Observer<Application>() {
            @Override
            public void onChanged(Application application) {
                activityPickUpBinding.tvDriverNamePickup.setText(
                        pickUpActivityViewModel.getUserMutableLiveData().getValue().getNickname());
                activityPickUpBinding.tvCarNumberPickup.setText(application.getLicensePlate());
                activityPickUpBinding.tvCarModelPickup.setText(
                        application.getCarModel()+"-"+application.getColor()+"色");
                activityPickUpBinding.tvPhonePickup.setText(
                        pickUpActivityViewModel.getUserMutableLiveData().getValue().getPhoneNumber());
            }
        });

        pickUpActivityViewModel.getDriverAccount().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d(TAG,s);
                if(!s.isEmpty()){
                    Log.d(TAG,"已与司机取得通讯");
                    Toast.makeText(context,"已与司机取得通讯",Toast.LENGTH_SHORT).show();
                }
            }
        });

        pickUpActivityViewModel.getIsPickUp().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    //关闭当前页面，开启新的导航页
                    DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    String lastTime = simpleDateFormat.format(date);
                    //存入时间
                    SpUtils.putString(context, "lastTime", lastTime);

                    setResult(1);
                    pickUpConfirmDialog.dismiss();
                    Log.d(TAG,"发车！");
                    finish();
                }
            }
        });

    }

    /**
     * 自定义上车点添加到地图上
     */
    private void addMarkerToMap(LatLng position,String textStr) {

        if (baiduMap == null) {
            return;
        }
//        baiduMap.clear();


        TextView textView = new TextView(context);

        textView.setText(textStr);
        textView.setBackgroundColor(Color.BLUE);
        textView.setTextColor(Color.WHITE);
        InfoWindow infoWindow = new InfoWindow(
                textView,
                position,
                -47);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(passengerBitmap)
                .position(position)
                .scaleX(0.5f).scaleY(0.5f).infoWindow(infoWindow);
        baiduMap.addOverlay(markerOptions);

    }

    @Override
    public void onResume() {
        activityPickUpBinding.mapviewPickUp.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        activityPickUpBinding.mapviewPickUp.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        baiduMap.setMyLocationEnabled(false);
        activityPickUpBinding.mapviewPickUp.onDestroy();
        if(null!=requestTimer) {
            requestTimer.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onStop()
    {
        // 关闭图层定位
        baiduMap.setMyLocationEnabled(false);
        super.onStop();
    }
}